package com.sangfor.ssl.service.utils.network;

import android.os.Build;
import android.text.TextUtils;
import androidx.core.os.EnvironmentCompat;
import com.sangfor.bugreport.logger.Log;
import com.sangfor.ssl.service.https.CertType;
import com.sangfor.ssl.service.https.CertificateVerifier;
import com.sangfor.ssl.service.https.FileInfo;
import com.sangfor.ssl.service.https.HttpRequest;
import com.sangfor.ssl.service.https.SFException;
import com.sangfor.ssl.service.setting.SettingManager;
import com.sangfor.ssl.service.setting.SystemConfiguration;
import com.sangfor.ssl.service.utils.IGeneral;
import com.sangfor.ssl.service.utils.IOUtils;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.impl.cookie.BasicClientCookie;

/* loaded from: classes2.dex */
public class HttpConnect {
    private static final String TAG = "HttpConnect";
    private boolean mAntiMITMEnable;
    private String mCipher;
    private List<BasicClientCookie> mCookieList;
    private long mGmVersion;
    protected SSLContext sslContext;
    private static List<BasicClientCookie> cookieList = new ArrayList();
    private static int BUFFER = 4096;
    private static byte[] B_ARRAY = new byte[4096];
    private int timeOut = 30;
    private boolean isUseCache = true;
    private boolean isDoOutput = true;
    private Map<String, String> headMap = new HashMap();
    private int responseCode = -1;
    private File uploadFile = null;
    private boolean isAddDevParam = true;
    private boolean mIsKeepLive = true;

    /* loaded from: classes2.dex */
    public static class TrustAnyHostnameVerifier implements HostnameVerifier {
        @Override // javax.net.ssl.HostnameVerifier
        public boolean verify(String str, SSLSession sSLSession) {
            return true;
        }
    }

    /* loaded from: classes2.dex */
    public static class TrustAnyTrustManager implements X509TrustManager {
        @Override // javax.net.ssl.X509TrustManager
        public void checkClientTrusted(X509Certificate[] x509CertificateArr, String str) throws CertificateException {
        }

        @Override // javax.net.ssl.X509TrustManager
        public void checkServerTrusted(X509Certificate[] x509CertificateArr, String str) throws CertificateException {
        }

        @Override // javax.net.ssl.X509TrustManager
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    }

    public HttpConnect() {
        this.sslContext = null;
        this.mAntiMITMEnable = false;
        this.mGmVersion = 0L;
        this.mCipher = null;
        addRequestHeader("User-Agent", IGeneral.USER_AGENT_VALUE_DEFAULT);
        if (Build.VERSION.SDK_INT < 9) {
            System.setProperty("http.keepAlive", "false");
            addRequestHeader("connection", SystemConfiguration.CONFIG_EFLAG_CLOSE);
        } else {
            addRequestHeader("connection", "keep-alive");
        }
        this.sslContext = null;
        this.mAntiMITMEnable = SystemConfiguration.getInstance().isAntiMITMOpen();
        this.mGmVersion = SystemConfiguration.getInstance().getGMMode();
        this.mCipher = SystemConfiguration.getInstance().getAuthCipher();
    }

    public void addCookie(BasicClientCookie basicClientCookie) {
        if (basicClientCookie.getName().equalsIgnoreCase("path")) {
            return;
        }
        cookieList.add(basicClientCookie);
    }

    public void delCookie(BasicClientCookie basicClientCookie) {
        cookieList.remove(basicClientCookie);
    }

    public List<BasicClientCookie> getAllCookie() {
        return cookieList;
    }

    public String getCookie(String str, String str2) {
        if (str != null && str2 != null) {
            try {
                String lowerCase = new URL(str).getHost().toLowerCase();
                for (BasicClientCookie basicClientCookie : cookieList) {
                    if (basicClientCookie.getDomain().equals(lowerCase) && basicClientCookie.getName().equals(str2)) {
                        return basicClientCookie.getValue();
                    }
                }
                return "";
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
        }
        return "";
    }

    public void setCookie(String str, String str2, String str3) {
        if (str == null || str2 == null) {
            return;
        }
        if (!str.startsWith(IGeneral.PROTO_HTTPS_HEAD) && !str.startsWith(IGeneral.PROTO_HTTP_HEAD)) {
            str = String.format(Locale.getDefault(), "https://%s", str);
        }
        BasicClientCookie basicClientCookie = null;
        try {
            URL url = new URL(str);
            Iterator<BasicClientCookie> it = cookieList.iterator();
            while (true) {
                if (!it.hasNext()) {
                    break;
                }
                BasicClientCookie next = it.next();
                if (next.getName().equals(str2) && next.getDomain().equals(url.getHost().toLowerCase())) {
                    next.setValue(str3);
                    basicClientCookie = next;
                    break;
                }
            }
            if (basicClientCookie == null) {
                BasicClientCookie basicClientCookie2 = new BasicClientCookie(str2, str3);
                basicClientCookie2.setDomain(url.getHost().toLowerCase());
                addCookie(basicClientCookie2);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

    public static void initializeCookies() {
        cookieList.clear();
    }

    public void setSSLContext(SSLContext sSLContext) {
        this.sslContext = sSLContext;
    }

    public void setTimeOut(int i) {
        if (i <= 0) {
            return;
        }
        this.timeOut = i;
    }

    public void setDoOutput(boolean z) {
        this.isDoOutput = z;
    }

    public void setUseCache(boolean z) {
        this.isUseCache = z;
    }

    public void setAddDevParam(boolean z) {
        this.isAddDevParam = z;
    }

    public void setUploadFile(File file) {
        this.uploadFile = file;
    }

    public int getTimeOut() {
        return this.timeOut;
    }

    public int getResponseCode() {
        return this.responseCode;
    }

    public void addRequestHeader(String str, String str2) {
        if (str == null) {
            return;
        }
        if (this.headMap.containsKey(str)) {
            this.headMap.remove(str);
        }
        this.headMap.put(str, str2);
    }

    private void applyRequestHeader(HttpURLConnection httpURLConnection) {
        if (httpURLConnection == null) {
            return;
        }
        for (String str : this.headMap.keySet()) {
            httpURLConnection.setRequestProperty(str, this.headMap.get(str));
        }
        applyCookieHeader(httpURLConnection);
    }

    private void applyCookieHeader(HttpURLConnection httpURLConnection) {
        String makeCookiesString = makeCookiesString(httpURLConnection.getURL().toString());
        if (makeCookiesString.length() > 0) {
            httpURLConnection.addRequestProperty(IGeneral.HTTP_HEAD_COOKIE, makeCookiesString);
        }
    }

    private String makeCookiesString(String str) {
        if (str == null) {
            return "";
        }
        try {
            String lowerCase = new URL(str).getHost().toLowerCase();
            StringBuilder sb = new StringBuilder();
            for (BasicClientCookie basicClientCookie : cookieList) {
                if (basicClientCookie.getDomain().equals(lowerCase)) {
                    if (sb.length() > 0) {
                        sb.append(";");
                    }
                    sb.append(basicClientCookie.getName());
                    sb.append("=");
                    sb.append(basicClientCookie.getValue());
                }
            }
            return sb.toString();
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return "";
        }
    }

    private void readResponseHeader(HttpURLConnection httpURLConnection) {
        List<String> list;
        if (httpURLConnection == null || (list = httpURLConnection.getHeaderFields().get(IGeneral.HTTP_HEAD_RES_COOKIE)) == null) {
            return;
        }
        for (String str : list) {
            boolean z = false;
            String[] split = str.split(";")[0].split("=");
            if (split.length == 2) {
                String str2 = split[0];
                String str3 = split[1];
                Iterator<BasicClientCookie> it = cookieList.iterator();
                while (true) {
                    if (!it.hasNext()) {
                        break;
                    }
                    BasicClientCookie next = it.next();
                    if (next.getName().equals(str2) && next.getDomain().equals(httpURLConnection.getURL().getHost().toLowerCase())) {
                        if (str3.toLowerCase().equals("deleted")) {
                            delCookie(next);
                        } else {
                            next.setValue(str3);
                        }
                        z = true;
                    }
                }
                if (!z) {
                    BasicClientCookie basicClientCookie = new BasicClientCookie(str2, str3);
                    basicClientCookie.setDomain(httpURLConnection.getURL().getHost().toLowerCase());
                    addCookie(basicClientCookie);
                    if (str2 != null && str2.equals(IGeneral.COOKIE_MBTWFID_STRING)) {
                        updateTwfidWithMobileTwfid(str3);
                    }
                }
            }
        }
    }

    private void updateTwfidWithMobileTwfid(String str) {
        setCookie((String) SettingManager.getInstance().getGlobalValue(SettingManager.GLOBAL_HOST_KEY), IGeneral.COOKIE_TWFID_STRING, str);
    }

    private String getDomainFromURL(String str) {
        if (str == null) {
            return null;
        }
        String[] split = str.split("//");
        if (split.length <= 1) {
            return null;
        }
        return split[1].split("/")[0].split(":")[0];
    }

    protected static StringBuilder makeStringBuilder(Map<String, String> map) {
        StringBuilder sb = new StringBuilder();
        if (map != null) {
            for (String str : map.keySet()) {
                if (sb.length() != 0) {
                    sb.append("&");
                }
                sb.append(str);
                sb.append("=");
                if (map.get(str) == null) {
                    sb.append("");
                } else {
                    sb.append(URLEncoder.encode(map.get(str)));
                }
            }
        }
        return sb;
    }

    protected static Map<String, String> makeUrlEncodeMap(Map<String, String> map) {
        HashMap hashMap = new HashMap();
        if (map != null) {
            for (String str : map.keySet()) {
                if (map.get(str) == null) {
                    hashMap.put(str, "");
                } else {
                    hashMap.put(str, URLEncoder.encode(map.get(str)));
                }
            }
        }
        return hashMap;
    }

    protected HttpURLConnection makeHttpConn(String str, String str2, int i, boolean z, boolean z2, boolean z3) throws Exception {
        HttpURLConnection httpURLConnection;
        if (str == null || str.length() == 0) {
            return null;
        }
        if (z3) {
            httpURLConnection = (HttpsURLConnection) new URL(str).openConnection();
            SSLContext sSLContext = this.sslContext;
            if (sSLContext == null) {
                TrustAnyTrustManager trustAnyTrustManager = new TrustAnyTrustManager();
                SSLContext sSLContext2 = SSLContext.getInstance("TLSv1.1");
                sSLContext2.init(null, new TrustManager[]{trustAnyTrustManager}, new SecureRandom());
                sSLContext = sSLContext2;
            }
            HttpsURLConnection httpsURLConnection = (HttpsURLConnection) httpURLConnection;
            httpsURLConnection.setSSLSocketFactory(sSLContext.getSocketFactory());
            httpsURLConnection.setHostnameVerifier(new TrustAnyHostnameVerifier());
        } else {
            httpURLConnection = (HttpURLConnection) new URL(str).openConnection();
        }
        httpURLConnection.setRequestMethod(str2);
        httpURLConnection.setDoOutput(z);
        httpURLConnection.setUseCaches(z2);
        httpURLConnection.setConnectTimeout(i);
        httpURLConnection.setReadTimeout(i);
        httpURLConnection.setInstanceFollowRedirects(false);
        return httpURLConnection;
    }

    public String requestStringWithURL(String str, Map<String, String> map) throws SFException {
        return requestStringWithURL(str, map, "POST", null, 0L);
    }

    public String requestStringWithURL(String str, Map<String, String> map, String str2) throws SFException {
        return requestStringWithURL(str, map, str2, null, 0L);
    }

    public String requestStringWithURL(String str, Map<String, String> map, String str2, String str3) throws SFException {
        return requestStringWithURL(str, map, str2, str3, SystemConfiguration.getInstance().getGMMode());
    }

    public String requestStringWithURL(String str, Map<String, String> map, String str2, String str3, long j) throws SFException {
        return requestStringWithURL(str, map, str2, null, null, CertType.CERT_TYPE_NONE, str3, j, null);
    }

    public String requestStringWithURL(String str, Map<String, String> map, String str2, String str3, String str4, CertType certType, String str5, long j, String str6) throws SFException {
        String str7;
        HttpRequest httpRequest;
        if (TextUtils.isEmpty(str)) {
            Log.warn(TAG, "url is empty,stacktrace:%s", Log.getExceptionContent(new Throwable()));
            throw new SFException("Url is empty.");
        }
        if (isHttpAddr(str) || isHttpsAddr(str)) {
            str7 = str;
        } else {
            str7 = IGeneral.PROTO_HTTP_HEAD + str;
        }
        if (this.isAddDevParam) {
            str7 = addParam(str7, "dev", IGeneral.PHONE_DEV, (String) SettingManager.getInstance().getGlobalValue(SettingManager.GLOBAL_LANGUAGE, IGeneral.CN_LANGUAGE));
        }
        try {
            try {
                if (str2.equals("POST")) {
                    if (this.uploadFile == null) {
                        httpRequest = HttpRequest.post(str7);
                        httpRequest.setPostBody(makeStringBuilder(map).toString());
                    } else {
                        httpRequest = HttpRequest.post(str7, makeUrlEncodeMap(map));
                        httpRequest.setPostFile(new FileInfo(this.uploadFile, String.format(Locale.getDefault(), "user=%s&vpn=%s&mobile=%s", (String) SettingManager.getInstance().get(SettingManager.SETTING_USERNAME, EnvironmentCompat.MEDIA_UNKNOWN), (String) SettingManager.getInstance().getGlobalValue(SettingManager.GLOBAL_HOST_KEY, EnvironmentCompat.MEDIA_UNKNOWN), Build.MODEL)));
                    }
                } else if (str2.equals("GET")) {
                    httpRequest = HttpRequest.get(str7, map);
                } else {
                    throw new SFException("invalid http type!");
                }
                if (str3 == null) {
                    httpRequest.setCipher(str5);
                    if (this.mAntiMITMEnable) {
                        httpRequest.setCertificateVerifier(new CertificateVerifier() { // from class: com.sangfor.ssl.service.utils.network.HttpConnect.1
                            @Override // com.sangfor.ssl.service.https.CertificateVerifier
                            public boolean verify(com.sangfor.ssl.service.https.SSLSession sSLSession) {
                                return TextUtils.equals(SystemConfiguration.getInstance().getMessageDigest(), sSLSession.getMessageDigest());
                            }
                        });
                    }
                } else {
                    if (certType == CertType.CERT_TYPE_GM) {
                        if (str6.equals("2")) {
                            httpRequest.setCipher(str5);
                        } else {
                            httpRequest.setCipher("ECDHE-SM2-SM4-SM3:ECC-SM2-SM4-SM3");
                        }
                    } else if (certType == CertType.CERT_TYPE_BUS) {
                        Log.info(TAG, "auto negotiate cipher!");
                    } else {
                        Log.info(TAG, "invalid certType");
                    }
                    httpRequest.setCert(str3, str4, certType);
                }
                if (j != 0) {
                    httpRequest.setGMVersion(j);
                }
                String makeCookiesString = makeCookiesString(str);
                if (!TextUtils.isEmpty(makeCookiesString)) {
                    httpRequest.setCookies(makeCookiesString);
                }
                httpRequest.setKeepAlive(this.mIsKeepLive);
                httpRequest.setFollowRedirects(true);
                httpRequest.setConnectTimeout(this.timeOut);
                long responseCode = httpRequest.getResponseCode();
                if (responseCode != 200) {
                    Log.warn(TAG, "http request responsecode error!!");
                    throw new SFException("Http connection failed, the response code is " + responseCode);
                }
                new HttpHeadReader(this).parseHttpHeaderN(httpRequest.getHeaders());
                String response = httpRequest.getResponse();
                IOUtils.closeQuietly(httpRequest);
                return response;
            } catch (SFException e) {
                throw e;
            } catch (IOException e2) {
                throw new SFException(e2.getMessage());
            }
        } catch (Throwable th) {
            IOUtils.closeQuietly((HttpRequest) null);
            throw th;
        }
    }

    public byte[] requestBytesWithURL(String str, Map<String, String> map, String str2, String str3) throws SFException {
        return requestWithURL(str, map, str2, str3, this.mGmVersion);
    }

    public byte[] requestWithURL(String str, Map<String, String> map, String str2, String str3, long j) throws SFException {
        String str4;
        HttpRequest httpRequest;
        if (TextUtils.isEmpty(str)) {
            Log.warn(TAG, "url is empty,stacktrace:%s", Log.getExceptionContent(new Throwable()));
            throw new SFException("MdmNetWork -> Url is empty.");
        }
        if (isHttpAddr(str) || isHttpsAddr(str)) {
            str4 = str;
        } else {
            str4 = IGeneral.PROTO_HTTP_HEAD + str;
        }
        if (this.isAddDevParam) {
            str4 = addParam(str4, "dev", IGeneral.PHONE_DEV, (String) SettingManager.getInstance().getGlobalValue(SettingManager.GLOBAL_LANGUAGE, IGeneral.CN_LANGUAGE));
        }
        try {
            try {
                if (str2.equals("POST")) {
                    if (this.uploadFile == null) {
                        httpRequest = HttpRequest.post(str4);
                        httpRequest.setPostBody(makeStringBuilder(map).toString());
                    } else {
                        httpRequest = HttpRequest.post(str4, makeUrlEncodeMap(map));
                        httpRequest.setPostFile(new FileInfo(this.uploadFile, String.format(Locale.getDefault(), "user=%s&vpn=%s&mobile=%s", (String) SettingManager.getInstance().get(SettingManager.SETTING_USERNAME, EnvironmentCompat.MEDIA_UNKNOWN), (String) SettingManager.getInstance().getGlobalValue(SettingManager.GLOBAL_HOST_KEY, EnvironmentCompat.MEDIA_UNKNOWN), Build.MODEL)));
                    }
                } else if (str2.equals("GET")) {
                    httpRequest = HttpRequest.get(str4, map);
                } else {
                    throw new SFException("invalid http type!");
                }
                httpRequest.setCipher(str3);
                if (this.mAntiMITMEnable) {
                    httpRequest.setCertificateVerifier(new CertificateVerifier() { // from class: com.sangfor.ssl.service.utils.network.HttpConnect.2
                        @Override // com.sangfor.ssl.service.https.CertificateVerifier
                        public boolean verify(com.sangfor.ssl.service.https.SSLSession sSLSession) {
                            return TextUtils.equals(SystemConfiguration.getInstance().getMessageDigest(), sSLSession.getMessageDigest());
                        }
                    });
                }
                if (j != 0) {
                    httpRequest.setGMVersion(j);
                }
                String makeCookiesString = makeCookiesString(str);
                if (!TextUtils.isEmpty(makeCookiesString)) {
                    httpRequest.setCookies(makeCookiesString);
                }
                httpRequest.setKeepAlive(this.mIsKeepLive);
                httpRequest.setFollowRedirects(true);
                httpRequest.setConnectTimeout(this.timeOut);
                long responseCode = httpRequest.getResponseCode();
                if (responseCode != 200) {
                    Log.warn(TAG, "http request responsecode error!!");
                    throw new SFException("Http connection failed, the response code is " + responseCode);
                }
                new HttpHeadReader().parseHttpHeaderN(httpRequest.getHeaders());
                byte[] readStream = readStream(httpRequest.getInputStream());
                IOUtils.closeQuietly(httpRequest);
                return readStream;
            } catch (SFException e) {
                throw e;
            } catch (IOException e2) {
                throw new SFException(e2.getMessage());
            }
        } catch (Throwable th) {
            IOUtils.closeQuietly((HttpRequest) null);
            throw th;
        }
    }

    public byte[] requestWithURL(String str, Map<String, String> map, String str2) throws SFException {
        return requestWithURL(str, map, str2, this.mCipher, this.mGmVersion);
    }

    private static String addParam(String str, String str2, String str3, String str4) {
        String str5 = "?";
        if (str.contains("?")) {
            str5 = (str.endsWith("?") || str.endsWith("&")) ? "" : "&";
        }
        return String.format("%s%s%s=%s&language=%s", str, str5, str2, str3, str4);
    }

    /* JADX WARN: Removed duplicated region for block: B:19:0x0032  */
    /*
        Code decompiled incorrectly, please refer to instructions dump.
        To view partially-correct code enable 'Show inconsistent code' option in preferences
    */
    private static byte[] readStream(java.io.InputStream r6) throws java.io.IOException {
        /*
            java.lang.String r0 = "network"
            java.io.ByteArrayOutputStream r1 = new java.io.ByteArrayOutputStream
            r1.<init>()
            r2 = 4096(0x1000, float:5.74E-42)
            byte[] r3 = new byte[r2]
            r4 = 0
            java.io.BufferedInputStream r5 = new java.io.BufferedInputStream     // Catch: java.io.IOException -> L22 java.io.FileNotFoundException -> L29
            r5.<init>(r6)     // Catch: java.io.IOException -> L22 java.io.FileNotFoundException -> L29
        L11:
            r6 = 0
            int r4 = r5.read(r3, r6, r2)     // Catch: java.io.IOException -> L1c java.io.FileNotFoundException -> L1f
            if (r4 < 0) goto L30
            r1.write(r3, r6, r4)     // Catch: java.io.IOException -> L1c java.io.FileNotFoundException -> L1f
            goto L11
        L1c:
            r6 = move-exception
            r4 = r5
            goto L23
        L1f:
            r6 = move-exception
            r4 = r5
            goto L2a
        L22:
            r6 = move-exception
        L23:
            java.lang.String r2 = "read input stream fail:IOException."
            com.sangfor.bugreport.logger.Log.warn(r0, r2, r6)
            goto L2f
        L29:
            r6 = move-exception
        L2a:
            java.lang.String r2 = "read input stream fail:FileNotFoundException."
            com.sangfor.bugreport.logger.Log.warn(r0, r2, r6)
        L2f:
            r5 = r4
        L30:
            if (r5 == 0) goto L35
            r5.close()
        L35:
            byte[] r6 = r1.toByteArray()
            return r6
        */
        throw new UnsupportedOperationException("Method not decompiled: com.sangfor.ssl.service.utils.network.HttpConnect.readStream(java.io.InputStream):byte[]");
    }

    public static boolean isHttpsAddr(String str) {
        return str.toLowerCase().indexOf(IGeneral.PROTO_HTTPS_HEAD) == 0;
    }

    public static boolean isHttpAddr(String str) {
        return str.toLowerCase().indexOf(IGeneral.PROTO_HTTP_HEAD) == 0;
    }
}
